Create an Express route to handle deletion of documents from a MongoDB collection.
Create an Express route to handle deletion of documents from a MongoDB collection.
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
27-Jul-2023Sure, here is an Express route to handle deletion of documents from a MongoDB collection:
JavaScript
This route first imports the
expressandmongodbmodules. It then defines the MongoDB connection URL, which ismongodb://localhost:27017/mydb.Next, the route defines a
gethandler for the/deleteroute. The handler takes areqandresobject as its input. Thereqobject contains the query parameters from the request, and theresobject is used to send the response back to the client.The
gethandler first connects to the MongoDB database and gets thepeoplecollection. The handler then gets theidof the document to be deleted from thereqobject.The handler then uses the
deleteOne()method to delete the document from the collection. ThedeleteOne()method returns a result object, which contains the number of documents that were deleted.If the document was deleted successfully, the handler sends a
200 OKresponse back to the client. Otherwise, the handler sends a404 Not Foundresponse back to the client.To run this route, you can save it as a file called
delete.jsand then run it from the command line:This will start the Express server on port 3000. You can then test the route by making a GET request to
http://localhost:3000/delete?id=1. If the document with the ID 1 exists in thepeoplecollection, it will be deleted. Otherwise, a404 Not Foundresponse will be returned.